/*
 * 文件名：BPSRequestFilter.java
 * 版权：Copyright 2006-2011 AsiaInfo Tech. Co. Ltd. All Rights Reserved. 
 * 描述： BPSRequestFilter.java
 * 修改人：齐鹏飞
 * 修改时间：2011-9-5
 * 修改内容：新增
 */
package com.fengxing.ams.web.common;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fengxing.ams.pub.util.LogUtil;
import com.fengxing.ams.pub.util.NumSequenceUtil;
import com.fengxing.ams.pub.vo.LogVO;

/**
 * BPS Request Context filter
 * <p>
 * BPS Request Context filter，用来记录BPS的请求上下文和LogID信息。
 * <p>
 * 
 * <pre>
 * </pre>
 * 
 * @author 齐鹏飞
 * @version CTMS V100R001 2011-9-5
 * @since CTMS V100R001C01
 */
@Component
public class BPSRequestFilter extends OncePerRequestFilter {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(BPSRequestFilter.class);

	/**
	 * 上下文管理
	 */
	private IContextManager contextManager;

	// private ILogService logService;

	/**
	 * 设置logService
	 * 
	 * @param logService
	 *            要设置的logService
	 */
	// @Resource
	// public void setLogService(ILogService logService) {
	// this.logService = logService;
	// }

	/**
	 * 设置contextManager
	 * 
	 * @param contextManager
	 *            要设置的contextManager
	 */
	@Resource
	public void setContextManager(IContextManager contextManager) {
		this.contextManager = contextManager;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest arg0,
			HttpServletResponse arg1, FilterChain arg2)
			throws ServletException, IOException {
		this.contextManager.setRequestParameters(arg0.getParameterMap());
		LogVO logVO = this.contextManager.getCdrVO();

		logVO.setStartTime(System.currentTimeMillis());

		String requestID = NumSequenceUtil.getUUID();

		this.contextManager.setRequestID(requestID);

		if (logger.isDebugEnabled()) {
			LogUtil.debug(
					logger,
					"doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain) - start"); //$NON-NLS-1$
		}

		try {
			arg2.doFilter(arg0, arg1);

			if (logger.isDebugEnabled()) {
				LogUtil.debug(logger,
						"doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain) - end"); //$NON-NLS-1$
			}
		} finally {
			this.contextManager.desctory();
		}

	}
}
